/**
 * 统一的API服务层
 * 基于后端提供的接口文档实现
 * 服务地址: http://localhost:8080
 * API前缀: /api/v1
 */

// API配置
const API_CONFIG = {
    BASE_URL: 'http://localhost:8080',
    API_PREFIX: '/api/v1',
    TIMEOUT: 10000
}

// 获取完整的API URL
const getApiUrl = (endpoint) => {
    return `${API_CONFIG.BASE_URL}${API_CONFIG.API_PREFIX}${endpoint}`
}

// 获取存储的JWT Token
const getToken = () => {
    return uni.getStorageSync('jwt_token') || ''
}

// 设置JWT Token
const setToken = (token) => {
    uni.setStorageSync('jwt_token', token)
}

// 清除JWT Token
const clearToken = () => {
    uni.removeStorageSync('jwt_token')
}

// 统一的请求方法
const request = (options) => {
    const {
        url,
        method = 'GET',
        data = {},
        needAuth = true,
        showLoading = false,
        loadingText = '加载中...'
    } = options

    // 显示加载提示
    if (showLoading) {
        uni.showLoading({
            title: loadingText,
            mask: true
        })
    }

    // 构建请求头
    const headers = {
        'Content-Type': 'application/json'
    }

    // 添加认证头
    if (needAuth) {
        const token = getToken()
        if (token) {
            headers['Authorization'] = `Bearer ${token}`
        }
    }

    return new Promise((resolve, reject) => {
        uni.request({
            url: getApiUrl(url),
            method,
            data,
            header: headers,
            timeout: API_CONFIG.TIMEOUT,
            success: (res) => {
                if (showLoading) {
                    uni.hideLoading()
                }

                console.log('API请求成功:', {
                    url: getApiUrl(url),
                    method,
                    data,
                    response: res
                })

                const { statusCode, data: responseData } = res

                // HTTP状态码检查
                if (statusCode !== 200) {
                    const errorMsg = `HTTP错误: ${statusCode}`
                    console.error(errorMsg, res)

                    // 尝试解析错误响应中的详细信息
                    let detailMsg = errorMsg
                    if (responseData && responseData.message) {
                        detailMsg = `${errorMsg} - ${responseData.message}`
                    } else if (responseData) {
                        detailMsg = `${errorMsg} - ${JSON.stringify(responseData)}`
                    }

                    reject(new Error(detailMsg))
                    return
                }

                // 业务状态码检查
                const { code, message, data: businessData } = responseData

                if (code === 200 || code === 201) {
                    // 成功
                    resolve({
                        code,
                        message,
                        data: businessData,
                        timestamp: responseData.timestamp
                    })
                } else if (code === 401) {
                    // Token过期或无效
                    console.warn('Token过期或无效，清除本地token')
                    clearToken()
                    reject(new Error(message || '认证失败'))
                } else {
                    // 其他业务错误
                    console.error('业务错误:', message)
                    reject(new Error(message || '请求失败'))
                }
            },
            fail: (err) => {
                if (showLoading) {
                    uni.hideLoading()
                }

                console.error('API请求失败:', {
                    url: getApiUrl(url),
                    method,
                    data,
                    error: err
                })

                let errorMsg = '网络请求失败'
                if (err.errMsg) {
                    if (err.errMsg.includes('timeout')) {
                        errorMsg = '请求超时，请检查网络连接'
                    } else if (err.errMsg.includes('fail')) {
                        errorMsg = '网络连接失败，请检查服务器状态'
                    }
                }

                reject(new Error(errorMsg))
            }
        })
    })
}

// 便捷的HTTP方法
const http = {
    get: (url, params = {}, options = {}) => {
        const queryString = Object.keys(params).length > 0
            ? '?' + Object.keys(params).map(key => `${key}=${encodeURIComponent(params[key])}`).join('&')
            : ''

        return request({
            url: url + queryString,
            method: 'GET',
            ...options
        })
    },

    post: (url, data = {}, options = {}) => {
        return request({
            url,
            method: 'POST',
            data,
            ...options
        })
    },

    put: (url, data = {}, options = {}) => {
        return request({
            url,
            method: 'PUT',
            data,
            ...options
        })
    },

    delete: (url, options = {}) => {
        return request({
            url,
            method: 'DELETE',
            ...options
        })
    }
}

// 导出API服务
export {
    http,
    getToken,
    setToken,
    clearToken,
    API_CONFIG
}

// 默认导出
export default http
